// pages/calculator/calculator.js
var address = require("../../js/mock")
const api = require('../../config/api.js');
// var util = require('../../utils/util');
const util = require('../../utils/util.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    //  确定按钮
    status: 0,
    // 计算器表单
    area:'',
    phone:'',
    name:'',
    // 室
    room:'',
    // 厅
    office:'',
    // 卫
    wc:'',
    // 户型data
    shows: false, //控制下拉列表的显示隐藏，false隐藏、true显示
    selectDatas: ['请选','1室', '2室', '3室', '4室'], //下拉列表的数据
    showst: false,
    selectDatast:['请选','1厅', '2厅', '3厅', '4厅'],
    indexs1: 0, //选择的下拉列 表下标,
    indexs2: 0, //选择的下拉列 表下标,
    indexs3: 0, //选择的下拉列 表下标,
    showsw: false,
    selectDatasw:['请选','1卫', '2卫', '3卫', '4卫'],
    // 表单
    sortCurrent: '',//
    upload_limit: 1,// 默认最多上传9张
    img_srcs: [], //如果是编辑状态，只需要把原信息的图片地址放到此处就可以显示出来
    img_src: [],
    content: [],//正文内容
    textreaHidden: true,
    addHidden: false,
    editVal: '',//编辑文字内容
    editIndex: '',//编辑的index
    userZoneList: [],//城市列表
    index2: '',//城市下标
    //城市
    animationAddressMenu: {},
    addressMenuIsShow: false,
    value: [0, 0, 0],
    provinces: [],
    citys: [],
    areas: [],
    consigneeName: "",
    consigneeRegion: "",
    detailedAddress: "",

  },
  // area
  bindinputarea(event){
    this.setData({
      area: event.detail.value,
  });
  },
  // phone
  bindinputphone(event){
    if (util.testMobile(event.detail.value)) {
      this.setData({
        phone: event.detail.value,
        status: 1
    });
  }

  },
    // name
bindinputname(event){
  this.setData({
    name: event.detail.value,
});
},
  // 去登录
  gotoLogin(){
    var that = this
    // // 地区
    // console.log(that.data.consigneeRegion)
    // // 面积
    // console.log(that.data.area+"㎡")
    // // 手机号
    // console.log(that.data.phone)
    // // 姓名
    // console.log(that.data.name)
    // // 室
    // console.log(that.data.room)
    // // 厅
    // console.log(that.data.room)
    // // 卫
    // console.log(that.data.wc)
    var userinfo=wx.getStorageSync('userInfo');
    // console.log(userinfo)
    let commonComputer={
      computerPhone:that.data.phone,
      computerHouse:that.data.room+that.data.room+that.data.wc,
      computerArea:that.data.area+"㎡",
      computerPlace:that.data.consigneeRegion,
      computerName:that.data.name
    }
    console.log(commonComputer)
    if(userinfo==''){
      wx.navigateTo({
        url: '/pages/app-auth/index',
      });
    }else{
      // 存入后端
      util.request(api.ComputerApi, commonComputer, 'POST').then(function (res) {
          console.log(res)
          if(res.code==20000){
            wx.showModal({
              title: '提示', //提示的标题
              content: '报价成功！！您的报价将通过短信发送到您的手机，注意查收！！！', //提示的内容
              showCancel: false,
              success: function(res) {
                if(res.confirm) {
                  console.log('用户点击了确定')
                  wx.switchTab({
                    url: '/pages/index/index',
                  })
                }
              }
            })
          }
      });

      
    }

  },
  

  // 点击下拉显示框
  selectTaps() {
    this.setData({
      shows: !this.data.shows,

    });
  },
  selectTapst() {
    this.setData({
      showst: !this.data.showst,

    });
  },
  selectTapsw() {
    this.setData({
      showsw: !this.data.showsw,

    });
  },
  // 点击室的下拉列表
  optionTaps(e) {
    var that=this
    let Indexs = e.currentTarget.dataset.index; //获取点击的下拉列表的下标
    console.log(Indexs)
    this.setData({
      indexs1: Indexs,
      shows: !this.data.shows
    });
    // that.data.indexs1+=1
    this.setData({
      room:that.data.indexs1+"室"
    })
// 点击厅的下拉列表
  },
  optionTapst(e) {
    var that=this
    let Indexs = e.currentTarget.dataset.index; //获取点击的下拉列表的下标
    console.log(Indexs)
    this.setData({
      indexs2: Indexs,
      showst: !this.data.showst
    });
    // that.data.indexs2+=1
    this.setData({
      office:that.data.indexs2+"厅"
    })

  },
   // 点击卫的下拉列表
   optionTapsw(e) {
    var that=this
    let Indexs = e.currentTarget.dataset.index; //获取点击的下拉列表的下标
    console.log(Indexs)
    this.setData({
      indexs3: Indexs,
      showsw: !this.data.showsw
    });
    // that.data.indexs3+=1
    this.setData({
      wc:that.data.indexs3+"卫"
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var id = address.provinces[0].id
    this.setData({
      provinces: address.provinces,
      citys: address.citys[id],
      areas: address.areas[address.citys[id][0].id],
    })
    //城市数据调用
    var id = address.provinces[0].id

    //wx.hideShareMenu();//隐藏分享
    //显示顶部加载动画
    wx.showNavigationBarLoading(
      console.log('页面加载开始'),
    );
    // wx.request({
    //   url: app.d.hostUrl + 'home.articleType',
    //   method: 'GET',
    //   header: {
    //     'Accept': 'application/json'
    //   },
    //   success: function (res) {
    //    // console.log(res)
    //     var data = res.data;
    //     that.setData({
    //       sortCurrent: data[0].id,
    //     })
    //    }
    // })
    //城市列表
    // wx.request({
    //   url: app.d.ceshiUrl + 'activity.areaList',
    //   success: function (res) {
    //     console.log(res.data)
    //     var res = res.data;
    //     that.setData({
    //       userZoneList: res,
    //     })
    //     wx.hideNavigationBarLoading();
    //   }
    // })
  },

  //所在城市选择
  bindPickerzone: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      index2: e.detail.value
    })
  },

  articlecurrentTap: function (e) {
    var that = this;
    console.log(e);
    that.setData({
      sortCurrent: e.target.id,
    })
  },
  addTap: function (e) {
    var that = this;
    if (that.data.addHidden == false) {
      that.setData({
        addHidden: true,
        editIndex: '',
        editVal: '',
      })
    } else {
      that.setData({
        addHidden: false,
        editIndex: '',
        editVal: '',
      })
    }
  },
  //上传图片
  chooseImg: function (e) {
    var that = this;
    wx.chooseImage({
      count: that.data.upload_limit,
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths;
        console.log(tempFilePaths)
        that.sendPhotos(tempFilePaths);
        console.log(that.data.content);
      }
    })
  },
  //发图片发送给后端服务器
  sendPhotos: function (tempFilePaths) {
    var that = this
    wx.showNavigationBarLoading();
    console.log(tempFilePaths[0])
    if (tempFilePaths.length !== 0) {
      wx.uploadFile({
        url: app.d.ceshiUrl + 'comment.uploadPic',
        filePath: tempFilePaths[0],
        name: 'picture',
        header: { "Content-Type": "multipart/form-data" },
        success: function (res) {
          console.log(res.data)
          var data = JSON.parse(res.data)
          console.log(data)
          var j = that.data.content.length;
          var content = that.data.content;
          if (data !== '') {
            var path = data.path;
            content[j] = {
              "name": "img",
              "contents": "https://xcx.fczxwl.com/attachment/" + path
            };
          }

          that.setData({
            content: content,
            addHidden: true
          });
          console.log(that.data.content)
          wx.hideNavigationBarLoading();
          tempFilePaths.splice(0, 1);

          // that.sendPhotos(tempFilePaths);
        },
        fail: function (res) {
          console.log('上传图片到服务器失败');
        },
        complete: function (res) {
          console.log(res);
        }
      })
    }
  },
  //图片预览
  previewImage: function (e) {
    var img_srcs = this.data.img_srcs;
    var index = e.target.dataset.index;
    wx.previewImage({
      current: img_srcs[index],
      urls: img_srcs           // 需要预览的图片http链接列表
    })
  },
  //删除内容快
  deletTap: function (e) {
    var that = this;
    console.log(e)
    var index = e.currentTarget.dataset.index;
    var content = that.data.content;
    wx.showModal({
      title: '提示',
      content: '确定要删除？',
      success: function (res) {
        if (res.confirm) {
          content.splice(index, 1)
          that.setData({
            content: content,
          })
        }
      }
    })
  },
  addTextTap: function (e) {
    var that = this;
    that.setData({
      textreaHidden: false,
    })
  },
  //文字textrea提交
  textreaSubmit: function (e) {
    var that = this;
    console.log(e.detail.value.textarea)
    var j = that.data.content.length;
    var content = that.data.content;
    var value = e.detail.value.textarea;
    console.log(value);//上传的内容
    //判断内容是否为空
    if (value !== "") {
      if (that.data.editIndex !== '') {
        //editIndex
        content[that.data.editIndex].contents = value;
      } else {
        content[j] = {
          "name": "text",
          "contents": value
        };
      }
      that.setData({
        textreaHidden: true,
        content: content,
        addHidden: true
      })
      console.log(that.data.content)
    } else {
      wx.showModal({
        title: '提示',
        content: '内容不能为空，请输入内容',
        success: function (res) {
          if (res.confirm) {
            return false;
          } else {
            that.setData({
              textreaHidden: true,
            })
          }
        }
      })
    }
  },
  //文字編輯
  editTap: function (e) {
    var that = this;
    console.log(e)
    var index = e.currentTarget.dataset.index;
    var content = that.data.content;
    that.setData({
      textreaHidden: false,
      editVal: content[index].contents,
      editIndex: index,
    })
  },

  //发布提交信息
  formSubmit: function (e) {
    wx.showNavigationBarLoading();
    var userInfo = wx.getStorageSync('userInfo');//用户基本信息
    var that = this;
    console.log(that.data.content);
    //console.log(e)
    var city = e.detail.value.city;//所在城市
    var area = e.detail.value.area;//房屋面积
    var phoneNumber = e.detail.value.phoneNumber;//手机号
    var userName = e.detail.value.userName;//姓名
    console.log(e.detail.value)
    var arr = {//正文内容
      "content": that.data.content
    }
    var typeid = that.data.sortCurrent;
    var typename;
    var mobile = /^[1][3,4,5,7,8][0-9]{9}$/;
    var isMobile = mobile.exec(e.detail.value.phoneNumber)
    //所有消息有任一为空时
    if (city == "" || area=="" || phoneNumber=="" || userName=="") {
      wx.showModal({
        title: '发布提示',
        content: '您的信息缺失，请重新填写！',
        showCancel: false,
        success: function (res) {
          if (res.confirm) {
            return false;
          }
        }
      })
      wx.hideNavigationBarLoading();
    }
    //判断电话号格式是否正确
    else if (!isMobile) {
      console.log('form表单发生点击事件，携带的数据为：', e.detail.value)
      console.log('电话：', e.detail.value.phoneNumber)
        wx.showModal({
          title: '提示！！',
          content: '你输入的电话不符，请重新检查填写',
         })
    }
    //当所有消息不为空
    else {
      //判断主要内容
      console.log(arr.content.length);
      if (arr.content.length == 0){
        wx.showModal({
          title: '发布提示',
          content: '文章内容不能为空，请编辑内容',
          showCancel: false,
          success: function (res) {
            if (res.confirm) {
              return false;
            }
          }
        })
        wx.hideNavigationBarLoading();
      }else{
        wx.request({
          url: app.d.hostUrl + 'activity.addApply',
          data: {
            "openid": wx.getStorageSync('openid'),
            "nickname": userInfo.nickName,   //昵称
            "avatar": userInfo.avatarUrl,  //头像
            // "title": title,
            "name": e.detail.value.userName,  //姓名
            "zone": e.detail.value.city,   //城市
            "area": e.detail.value.area,   //手机号
            "tel": e.detail.value.phoneNumber,   //手机号
            "content": arr,  //内容
          },
          method: 'GET',
          header: {
            'Accept': 'application/json'
          },
          success: function (res) {
            console.log(res)
            wx.hideNavigationBarLoading();
            wx.showToast({
              title: '已提交报名',
              icon: 'success',
              duration: 2000,
              success: function () {
                setTimeout(function () {
                  wx.reLaunch({
                    url: '/pages/activity/home/home',
                  })
                }, 2000)
              }
            })
          }
        })
      }
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var animation = wx.createAnimation({
      duration: 500,
      timingFunction: 'linear',
    })
    this.animation = animation
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    if (res.from === "button") {
      console.log("来自页面内转发按钮");
      console.log(res.target);
    } else {
      console.log("来自右上角转发菜单")
    }
    return {
      title: '嘿，装修',
      path: '/pages/index/index?shareid=' + wx.getStorageSync("openid"),
      success: (res) => {
        console.log("转发成功", res);
      },
      fail: (res) => {
        console.log("转发失败", res);
      }
    }

  },
   // 点击所在地区弹出选择框
   select: function (e) {
    // 如果已经显示，不在执行显示动画
    if (this.data.addressMenuIsShow) {
      return false
    } else {
      // 执行显示动画
      this.startAddressAnimation(true)
    }
  },
  // 执行动画
  startAddressAnimation: function (isShow) {
    if (isShow) {
      // vh是用来表示尺寸的单位，高度全屏是100vh
      this.animation.translateY(0 + 'vh').step()
    } else {
      this.animation.translateY(40 + 'vh').step()
    }
    this.setData({
      animationAddressMenu: this.animation.export(),
      addressMenuIsShow: isShow,
    })
  },
  // 点击地区选择取消按钮
  cityCancel: function (e) {
    this.startAddressAnimation(false)
  },
  // 点击地区选择确定按钮
  citySure: function (e) {
    var that = this
    var city = that.data.city
    var value = that.data.value
    this.startAddressAnimation(false)
    // 将选择的城市信息显示到输入框
    var consigneeRegion = that.data.provinces[value[0]].name + '-' + that.data.citys[value[1]].name + '-' + that.data.areas[value[2]].name
    that.setData({
      consigneeRegion: consigneeRegion,
    })
  },
  // 处理省市县联动逻辑
  cityChange: function (e) {
    var value = e.detail.value
    var provinces = this.data.provinces
    var citys = this.data.citys
    var areas = this.data.areas
    var provinceNum = value[0]
    var cityNum = value[1]
    var countyNum = value[2]
    // 如果省份选择项和之前不一样，表示滑动了省份，此时市默认是省的第一组数据，
    if (this.data.value[0] != provinceNum) {
      var id = provinces[provinceNum].id
      this.setData({
        value: [provinceNum, 0, 0],
        citys: address.citys[id],
        areas: address.areas[address.citys[id][0].id],
      })
    } else if (this.data.value[1] != cityNum) {
      // 滑动选择了第二项数据，即市，此时区显示省市对应的第一组数据
      var id = citys[cityNum].id
      this.setData({
        value: [provinceNum, cityNum, 0],
        areas: address.areas[citys[cityNum].id],
      })
    } else {
      // 滑动选择了区
      this.setData({
        value: [provinceNum, cityNum, countyNum]
      })
    }
  },
})

